package org.apache.rmiloader.kernel;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;
import org.apache.rmiloader.util.RmiLoaderConfig;
import org.apache.rmiloader.util.StringPropertyReplacer;

/**
 * Find jar files and provide a list to reach them
 * @author Joris
 *
 */
public class JarFinder {

	 /** Logger Initialization */
    private Logger logger = Logger.getLogger(JarFinder.class);
    
    private final String[] tomcatJars = { "annotations-api.jar", "catalina.*.jar", 
    									"ecj-.*.jar", "el-api.jar", "jasper.*.jar", "jsp-api.jar", 
    									"servlet-api.jar", "tomcat-.*" };
    
    private Set<String> libPaths = new HashSet<String>();
    private Set<String> jarFiles = new HashSet<String>();
       
    public JarFinder()
    {
    	initLibPaths();
    	initJarFiles();
    }
    
    private void initLibPaths()
    {
    	if (System.getProperty(RmiLoaderConfig.CATALINA_BASE) == null) {
			logger.warn("[" + RmiLoaderConfig.CATALINA_BASE + "] should be defined. Are you sure to use this app in Tomcat env. ?");
		}
    	if (System.getProperty(RmiLoaderConfig.CATALINA_HOME) == null) {
    		logger.warn(RmiLoaderConfig.CATALINA_HOME + " should be defined. Are you sure to use this app in Tomcat env. ?");
    	}
		String paths = System.getProperty(RmiLoaderConfig.COMMON_LOADER);
		if (paths == null) {
    		String msg = RmiLoaderConfig.COMMON_LOADER + " should be defined. Are you sure to use this app in Tomcat env. ?";
			logger.error(msg);
    		throw new RuntimeException(msg);
		}
		// replace ${property} by value
		paths = StringPropertyReplacer.replaceProperties(paths);
		// split string
		String[] tabPaths = paths.split(",");
		// remove duplicate path definition by Set feature and remove jar files definition in path (*.jar)
		for (String path : tabPaths) {
			if (new File(path).isDirectory()) {
				libPaths.add(path);
			}
		}
		
		// Print INFO Log
		logger.info(libPaths.size() + " paths have been found");
		for (String path : libPaths) {
			logger.info("path found - " + path);
		}
    }
    
    private void initJarFiles()
    {
    	// Check out unknown jar
    	for (String path : libPaths) {
    		String[] jars = new File(path).list();
    		for (String jar : jars) {
    			if (jar.matches(".*\\.jar")) {	
    				boolean isNotTomcat = true;
    				for (String tomcatJar : tomcatJars) {
    					if (jar.matches(tomcatJar)) {
    						isNotTomcat = false;
    						break ;
    					}
    				}
    				if (isNotTomcat)
    					jarFiles.add(path + "/" + jar);
    			}
    		}
    	}
    	
    	// Print INFO Log
    	logger.info(jarFiles.size() + " jars have been found");
		for (String path : jarFiles) {
			logger.info("jar found - " + path);
		}
    }
    
    public Set<String> getJarFiles()
    {
    	return jarFiles;
    }
}
